import { OpenFile, Store, StoreHandler } from "../../core";

import DownloadButton from "./DownloadButton";
import downloadFile from "./downloadFile";
import { StoreProps } from "./interface";
import { FC, ReactElement, useEffect, useState } from "react";

export interface RenderDownloadProps {
  onClick: () => void;
}

export type RenderDownload = (props: RenderDownloadProps) => ReactElement;

export interface DownloadProps {
  children?: RenderDownload;
}

const Download: FC<{
  children?: RenderDownload;
  fileNameGenerator: (file: OpenFile) => string;
  store: Store<StoreProps>;
}> = ({ children, fileNameGenerator, store }) => {
  const [currentFile, setCurrentFile] = useState<OpenFile | undefined>(
    store.get("file")
  );

  const handleFileChanged: StoreHandler<OpenFile> = (file: OpenFile) => {
    setCurrentFile(file);
  };

  useEffect(() => {
    store.subscribe("file", handleFileChanged);

    return () => {
      store.unsubscribe("file", handleFileChanged);
    };
  }, []);

  const download = () => {
    if (currentFile) {
      downloadFile(currentFile, fileNameGenerator(currentFile));
    }
  };

  const defaultChildren = (props: RenderDownloadProps) => (
    <DownloadButton onClick={props.onClick} />
  );
  const render = children || defaultChildren;

  return render({
    onClick: download,
  });
};

export default Download;
